require.config({
    baseUrl: "./modules",
    paths: {
        jq: "../libs/jquery.2.2.4"
    }
})
require(["jq", "getGoods", "renderCart", "setNum", "setdel", "setCheck", "AllCheck", "sumNum", "sumPrice", "delCheck"], function (_, getGoods, renderCart, setNum, setdel, setCheck, AllCheck, sumNum, sumPrice, delCheck) {
    let goodsMsg = localStorage.getItem("goodsMsg") ? JSON.parse(localStorage.getItem("goodsMsg")) : [];
    $("#allFlag")[0].checked = goodsMsg.length < 1 ? false : goodsMsg.every(val => val.check);
    // 2：请求商品数据
    getGoods((res) => {
        // 3:渲染页面
        renderCart(res, goodsMsg);
    })
    // 4：修改数据-获取输入框，事件委托绑定事件
    $(".bd").on("input", ".setNum", function () {
        const id = $(this).parent().parent().attr("index");
        setNum(id, goodsMsg, $(this).val())
        $("#allNum").html(sumNum(goodsMsg))
        $("#allPrice").html(sumPrice(goodsMsg))
        // $(".sub").html(sumSub(goodsMsg));
        getGoods((res) => {
            renderCart(res, goodsMsg, (i) => {
                goodsMsg[i].num
            });
        })
    });
    // 5:删除事件-事件委托删除按钮事件
    $(".bd").on("click", ".delBtn", function () {
        $(this).parent().parent().remove()
        const id = $(this).parent().parent().attr("index");
        setdel(id, goodsMsg)
        $("#allNum").html(sumNum(goodsMsg))
        // 计算总价格
        $("#allPrice").html(sumPrice(goodsMsg))
        $("#allFlag")[0].checked = goodsMsg.length < 1 ? false : goodsMsg.every(val => val.check);
    })
    // 7：输入框的选中
    $(".bd").on("change", ".check", function () {
        const id = $(this).parent().parent().attr("index");
        const c = this.checked;
        setCheck(goodsMsg, id, function (i) {
            goodsMsg[i].check = c
        })
        // 判断是否需要全选
        $("#allFlag")[0].checked = goodsMsg.length < 1 ? false : goodsMsg.every(val => val.check);
        $("#allNum").html(sumNum(goodsMsg))
        $("#allPrice").html(sumPrice(goodsMsg))
    })
    // 全选影响当个商品的选择
    $("#allFlag").change(function () {
        const that = this;
        AllCheck(goodsMsg, that)
        $("#allNum").html(sumNum(goodsMsg))
        $("#allPrice").html(sumPrice(goodsMsg))
    })
    // 计算总数量
    $("#allNum").html(sumNum(goodsMsg))
    // 计算总价格
    $("#allPrice").html(sumPrice(goodsMsg))
    // 删除选中的商品
    $("#delShop").click(() => {
        goodsMsg = delCheck(goodsMsg);
        getGoods((res) => {
            renderCart(res, goodsMsg);
        })
        $("#allNum").html(0)
        // 计算总价格
        $("#allPrice").html(0)
        $("#allFlag")[0].checked = goodsMsg.length < 1 ? false : goodsMsg.every(val => val.check);
    })
})